<template>
  <div class="canvas-board" @dragover.prevent @drop="onDrop">
    <div ref="mapContainer" class="map-container"></div>
    <canvas ref="canvas" :width="width" :height="height" @click="onCanvasClick"></canvas>
    <PropertiesPanel @apply-changes="drawElements" @delete-element="removeMarker" />
  </div>
</template>

<script>
import PropertiesPanel from './PropertiesPanel';
import { mapState } from 'vuex';

export default {
  name: 'CanvasBoard',
  components: {
    PropertiesPanel
  },
  data() {
    return {
      width: 980,
      height: 750,
      map: null,
      markers: {} // 用于存储地图标记
    };
  },
  computed: {
    ...mapState(['elements', 'selectedElement'])
  },
  watch: {
    elements: {
      handler(newElements) {
        this.updateMarkers(newElements);
        this.drawElements();
      },
      deep: true
    },
    selectedElement: {
      handler(newSelected) {
        if (newSelected) {
          this.updateMarker(newSelected);
          this.drawElements();
        }
      },
      deep: true
    }
  },
  mounted() {
    this.initMap();
    this.context = this.$refs.canvas.getContext('2d');
    this.drawElements();
  },
  methods: {
    initMap() {
      if (typeof AMap === 'undefined') {
        console.error('AMap is not defined. Make sure the AMap JavaScript SDK is loaded.');
        return;
      }

      this.$refs.mapContainer.style.width = `${this.width}px`;
      this.$refs.mapContainer.style.height = `${this.height}px`;

      // 初始化高德地图
      this.map = new AMap.Map(this.$refs.mapContainer, {
        zoom: 10,
        center: [121.4737, 31.2304], // 上海坐标
        viewMode: '2D',
      });
    },
    onDrop(event) {
      const icon = JSON.parse(event.dataTransfer.getData('icon'));
      const rect = this.$refs.mapContainer.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      const lnglat = this.map.containerToLngLat(new AMap.Pixel(x, y)); // 将屏幕坐标转换为地图经纬度
      this.addMarker(icon, lnglat);
    },
    addMarker(icon, lnglat) {
      const id = Date.now();
      const speed = 1;
      // 创建高德地图标记
      const marker = new AMap.Marker({
        position: lnglat,
        content: `<div style="position: relative; text-align: center;">
                    <img src="${icon.src}" style="width:50px;height:50px;" />
                    <div style="position: absolute; width: 100%; top: 55px; font-size: 12px; color: red;">${icon.name}</div>
                  </div>`,
        offset: new AMap.Pixel(-25, -25) // 图片中心对准位置
      });

      marker.setMap(this.map);

      // 监听标记点击事件
      marker.on('click', () => {
        this.$store.commit('selectElement', {
          ...icon,
          lng: lnglat.lng,
          lat: lnglat.lat,
          speed: speed,
          id: id
        });
      });

      // 将标记信息存储到 Vuex 中
      this.$store.commit('addElement', {
        ...icon,
        lng: lnglat.lng,
        lat: lnglat.lat,
        speed: speed,
        id: id
      });

      // 保存到 markers 对象中
      this.markers[id] = marker;
    },
    updateMarkers(newElements) {
      // 删除不存在的元素标记
      Object.keys(this.markers).forEach(id => {
        if (!newElements.some(el => el.id === Number(id))) {
          this.markers[id].setMap(null);
          delete this.markers[id];
        }
      });

      // 更新和添加新标记
      newElements.forEach(element => {
        if (this.markers[element.id]) {
          this.updateMarker(element);
        } else {
          this.addMarker(element, new AMap.LngLat(element.lng, element.lat));
        }
      });
    },
    updateMarker(element) {
      const marker = this.markers[element.id];
      if (marker) {
        marker.setPosition(new AMap.LngLat(element.lng, element.lat));
        marker.setContent(`<div style="position: relative; text-align: center;">
          <img src="${element.src}" style="width:50px;height:50px;" />
          <div style="position: absolute; width: 100%; top: 55px; font-size: 12px; color: red;">${element.name}</div>
        </div>`);
      }
    },
    drawElements() {
      this.context.clearRect(0, 0, this.width, this.height);
      this.elements.forEach(element => this.drawElement(element));
    },
    drawElement(element) {
      const img = new Image();
      img.src = element.src;
      img.onload = () => {
        this.context.drawImage(img, element.x, element.y, 50, 50);
        this.context.font = '12px Arial';
        this.context.textAlign = 'center';
        this.context.fillStyle = 'black';
        this.context.fillText(element.name, element.x + 25, element.y + 65);
      };
    },
    onCanvasClick(event) {
      const rect = this.$refs.canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      const element = this.elements.find(el =>
        x >= el.x && x <= el.x + 50 && y >= el.y && y <= el.y + 50
      );
      if (element) {
        this.$store.commit('selectElement', element);
      } else {
        this.$store.commit('selectElement', null);
      }
    },
    removeMarker(id) {
      if (this.markers[id]) {
        this.markers[id].setMap(null);
        delete this.markers[id];
      }
    }
  }
};
</script>

<style scoped>
.canvas-board {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 100%;
  height: 100vh; /* 确保画板的高度适应视口高度 */
}

.map-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 1px solid #000;
  z-index: 2;
  pointer-events: none;
}
</style>
